<template>
  <MainLayout>
    <router-view></router-view>
    <div class="role-management">
    <h2>角色管理</h2>

    <!-- 搜索 -->
    <el-form :inline="true" class="add-role-form">
      <el-form-item v-if="!isNoShowAdvancedSearch">
        <el-input v-model="fuzzyQuery" placeholder="请输入角色名称/角色编码" />
      </el-form-item>
      <el-form-item>
        <template v-if="isNoShowAdvancedSearch">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="角色名称" :label-width="70">
                <el-input v-model="newRole.name" placeholder="请输入角色名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="角色编码" :label-width="70">
                <el-input v-model="newRole.code" placeholder="请输入角色编码" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="角色描述" :label-width="70">
                <el-input v-model="newRole.description" placeholder="请输入角色描述" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="状态" :label-width="70">
                <el-select v-model="newRole.status" placeholder="请选择状态" style="width: 100px;">
                  <el-option label="启用" :value="1" />
                  <el-option label="禁用" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button type="text" style="width: 80px;" @click="toggleAdvancedSearch">
          {{ isNoShowAdvancedSearch ? '收起' : '高级搜索' }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-form :inline="true" style="float: right;">
      <el-form-item>
        <el-button type="primary" @click="openDialog('create')">添加角色</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 角色列表 -->
    <el-table
        :data="roles"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="code" label="角色编码" />
      <el-table-column prop="description" label="角色描述" />
      <!-- 使用状态标签组件 -->
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <status-tag :status="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click.stop="openDialog('edit', scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click.stop="deleteRole(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
    />

    <!-- 使用分页组件 -->
    <pagination
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @page-change="handlePageChange"
    />

    <!-- 使用表单对话框组件 -->
    <form-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      :form-data="currentRole"
      @cancel="dialogVisible = false"
      @save="saveRole"
    >
      <el-form-item label="角色名称">
        <el-input v-model="currentRole.name" placeholder="请输入角色名" />
      </el-form-item>
      <el-form-item label="角色编码">
        <el-input v-model="currentRole.code" placeholder="请输入角色编码" />
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="currentRole.description" placeholder="请输入角色描述" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="currentRole.status" placeholder="请选择状态" style="width: 100px;">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
    </form-dialog>

    <!-- 详情模态框 -->
    <el-dialog v-model="isViewingDetail" title="角色详情" width="40%">
      <el-form :model="roleDetail" label-width="100px" label-position="left">
        <el-form-item label="角色名称">
          <el-input v-model="roleDetail.name" readonly />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="roleDetail.code" readonly />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleDetail.description" readonly />
        </el-form-item>
        <el-form-item label="状态">
          <el-tag :type="roleDetail.status === 1 ? 'success' : 'danger'">
            {{ roleDetail.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isViewingDetail = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
  </MainLayout>

</template>

<script>
import Pagination from '@/components/common/Pagination.vue';
import StatusTag from '@/components/common/StatusTag.vue';
import FormDialog from '@/components/common/FormDialog.vue';
import MainLayout from '@/layouts/MainLayout.vue'

export default {
  components: {
    Pagination,
    StatusTag,
    FormDialog,
    MainLayout
  },
  data() {
    return {
      roles: [],
      total: 0,
      currentPage: 1,
      pageSize: 5,

      dialogVisible: false,
      dialogMode: '', // 'create' or 'edit'
      currentRole: this.defaultRole(),

      newRole: {
        pageNo: 1,
        pageSize: 10,
        name: '',
        code: '',
        description: '',
        status: null,
      },

      fuzzyQuery: '',
      isNoShowAdvancedSearch: false,

      selectedRoles: [],
      isViewingDetail: false,
      roleDetail: {},
    };
  },
  computed: {
    dialogTitle() {
      return this.dialogMode === 'create' ? '新增角色' : '编辑角色';
    },
  },
  mounted() {
    this.fetchRoles();
    console.log('Mounted, roles:', this.roles);
  },
  methods: {
    defaultRole() {
      return {
        id: null,
        name: '',
        code: '',
        description: '',
        status: 1,
      };
    },

    openDialog(mode, role = {}) {
      this.dialogMode = mode;
      this.currentRole = mode === 'edit' ? { ...role } : this.defaultRole();
      this.dialogVisible = true;
    },

    async saveRole() {
      const url = this.dialogMode === 'create' ? 'http://localhost:8090/role/C' : 'http://localhost:8090/role/UById';

      try {
        const requestData = this.dialogMode === 'create' ? 
          { ...this.currentRole, id: undefined } : 
          this.currentRole;

        const response = await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(requestData),
        });

        const data = await response.json();
        if (data.code == 200) {
          this.dialogVisible = false;
          this.$message.success(`${this.dialogTitle}成功`);
          this.fetchRoles();
        } else {
          this.$message.error(`${this.dialogTitle}失败`);
        }
      } catch (err) {
        console.error(`${this.dialogTitle}失败:`, err);
        this.$message.error(`发生错误`);
      }
    },

    async fetchRoles() {
      try {
        const response = await fetch('http://localhost:8090/role/P', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            pageNo: this.currentPage,
            pageSize: this.pageSize,
            name: this.newRole.name,
            code: this.newRole.code,
            description: this.newRole.description,
            status: this.newRole.status,
          }),
        });

        const data = await response.json();
        console.log('API Response:', data);
        if (data.code == 200) {
          this.roles = data.data.records;
          this.total = data.data.total;
          console.log('Roles after update:', this.roles);
        } else {
          console.error('获取角色数据失败:', data.message);
          this.$message.error(`获取角色数据失败: ${data.message}`);
        }
      } catch (err) {
        console.error('获取角色数据失败:', err);
        this.$message.error('获取角色数据失败，请检查网络连接');
      }
    },

    async deleteRole(id) {
      try {
        const response = await fetch(`http://localhost:8090/role/DById/${id}`, { method: 'GET' });
        const data = await response.json();

        if (data.code == 200) {
          this.roles = this.roles.filter(r => r.id !== id);
          this.$message.success('删除成功');
        } else {
          this.$message.error('删除失败');
        }
      } catch (err) {
        console.error('删除失败:', err);
        this.$message.error('出错啦');
      }
    },

    batchDelete() {
      const ids = this.selectedRoles.map(r => r.id);
      this.$confirm('确定要删除选中的角色吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          const response = await fetch('http://localhost:8090/role/DByIds', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(ids),
          });

          const data = await response.json();
          if (data.code == 200) {
            this.roles = this.roles.filter(r => !ids.includes(r.id));
            this.selectedRoles = [];
            this.$message.success('批量删除成功');
          } else {
            this.$message.error('批量删除失败');
          }
        } catch (err) {
          console.error('批量删除失败:', err);
          this.$message.error('出错啦');
        }
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' });
      });
    },

    handleRowClick(row) {
      this.roleDetail = row;
      this.isViewingDetail = true;
    },

    handleSelectionChange(selection) {
      this.selectedRoles = selection;
    },

    handlePageChange(page) {
      this.currentPage = page;
      this.fetchRoles();
    },

    toggleAdvancedSearch() {
      this.isNoShowAdvancedSearch = !this.isNoShowAdvancedSearch;
      if (!this.isNoShowAdvancedSearch) {
        this.newRole.name = '';
        this.newRole.status = null;
      }
    },

    onSearch() {
      this.currentPage = 1;
      this.fetchRoles();
    },
  },
};
</script>

<style scoped>
/* 原样式保持不变 */
.role-management {
  width: 100%;
  min-height: 100vh;
  margin: 0;
  padding: 30px;
  background-color: #fff;
  padding-bottom: 100px;
}
.pagination {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 30px;
  margin-top: 24px;
  justify-content: center;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}
</style>
